package edu.fub.pub2search.ws;

import edu.fub.pub2search.db.CircularRangeFilter;
import edu.fub.pub2search.db.DataAccess;
import edu.fub.pub2search.db.Pub;
import edu.fub.pub2search.geo.GeoCalculator;
import edu.fub.pub2search.geo.GeoPosition;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class PubSearcher {
	
	/* Data access object */
	private DataAccess dataAccess;
	
	/**
	 * Default constructor.
	 */
	public PubSearcher() {
		try {
			// get the connection to the MySQL database
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://localhost/pub2search";
			Connection conn = DriverManager.getConnection(url, "root", "josejose");
			
			// set the data access
			dataAccess = new DataAccess(conn);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	/**
	 * Returns an array of <i>Pub</i> that locates within the radius measured from
	 * a given source coordinate in [latitude, longitude]. This coordinate can be
	 * assumed as the current position of a person.
	 * 
	 * @param latitude The latitude of the source (in micro-degrees).
	 * @param longitude The longitude of the source (in micro-degrees).
	 * @param radius The distance from the central point (in kilometers).
	 * @return Returns an array of <i>Pub</i> that locates within the radius.
	 * @throws SQLException
	 */
	public Pub[] getPubWithinRadius(int latitude, int longitude, double radius) {
		
		GeoPosition source = new GeoPosition(latitude, longitude);
				
		// mark the outside points of the circle.
		GeoPosition p0 = GeoCalculator.destinationPosition(source, 0, radius);
		GeoPosition p1 = GeoCalculator.destinationPosition(source, 90, radius);
		GeoPosition p2 = GeoCalculator.destinationPosition(source, 180, radius);
		GeoPosition p3 = GeoCalculator.destinationPosition(source, 270, radius);
					
		// set up the filter.
		CircularRangeFilter filter = new CircularRangeFilter(source, radius);
		
		// query to the database.
		Pub[] result =  dataAccess.getPub(p0.x, p2.x, p1.y, p3.y, filter);
		
		return result;		
	}
}